//
//  RegistVC.swift
//  DianXia
//
//  Created by you&me on 2017/12/15.
//  Copyright © 2017年 you&me. All rights reserved.
//

import UIKit

class RegistVC: UIViewController {

    @IBOutlet weak var name: UITextField!
    @IBOutlet weak var phone: UITextField!
    @IBOutlet weak var superiorPhone: UITextField!
    @IBOutlet weak var phoneCode: UITextField!
    @IBOutlet weak var applyBtn: UIButton!
    @IBOutlet weak var backBtn: UIButton!
    @IBOutlet weak var codeBtn: UIButton!
    
    let dispose = DisposeBag()
    let loginVM = LoginVM()

    override func viewDidLoad() {
        super.viewDidLoad()
        //姓名的观察转换
        let nameObser = name.rx.text.orEmpty
                            .asObservable()
                            .map { $0.count > 0 }
                            .share(replay: 1)
         //手机号码
        let phoneObser = phone.rx.text.orEmpty
                             .asObservable()
                             .map { $0.validateText(.PhoneNumber) }
                             .share(replay: 1)
         //上级主管的电话号码
        let upPhoneObser = superiorPhone.rx.text.orEmpty
                                        .asObservable()
                                        .map { $0.validateText(.PhoneNumber) }
                                        .share(replay: 1)
        //验证码
        let code = phoneCode.rx.text.orEmpty
            .asObservable()
            .map { $0.count == 5 }
            .share(replay: 1)

        //合成新的信号 并与 申请按钮绑定
        let comObser = Observable.combineLatest(nameObser, phoneObser, upPhoneObser, code) { $0 && $1 && $2 && $3 }
        comObser.bind(to: applyBtn.ex_State)
                .disposed(by: dispose)

        //手机号与发送验证码
        phoneObser.bind(to: codeBtn.ex_State)
                  .disposed(by: dispose)

        //获取验证码的操作 controlEvent 控制事件
        codeBtn.rx.tap
            .subscribe({ [weak self] _ in self?.loginVM.getLoginPhoneCode(self?.phone.text ?? "" , "regist") })
            .disposed(by: dispose)

        // 注册的点击事件
        applyBtn.rx.tap
            .subscribe({ [weak self] _ in  self?.regist() })
            .disposed(by: dispose)

        // 返回按钮的点击事件
        backBtn.rx.tap
            .subscribe({ [weak self] _ in self?.dismiss(animated: true, completion: nil) })
            .disposed(by: dispose)
    }

    fileprivate func regist() {
        self.loginVM.regist(name.text!, phone.text!, superiorPhone.text!, phoneCode.text!) {
            self.dismiss(animated: true, completion: nil)
        }

    }

}
